//
//  L9_CarModel.m
//  NewBleDemo
//
//  Created by cjg on 2019/11/7.
//  Copyright © 2019 cjg. All rights reserved.
//

#import "L9_CarModel.h"
#import "IMTCANManager.h"

NSString * const L9_CarModelErrorCodeDomain = @"L9_CarModelErrorCodeDomain";  

@implementation L9_CarModel

// 只读无参数
- (void)getDataWithCmdType:(L9_CarModelCmdType)cmdType isRepeat:(BOOL)isRepeat compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    [self sendMessageWithCmdType:cmdType dataParam:nil isRead:YES isRepeat:isRepeat repeatcount:0 compleBlock:compleBlock];
}

// 读取带参数
- (void)getDataWithCmdType:(L9_CarModelCmdType)cmdType dataParam:(uint8_t)param isRepeat:(BOOL)isRepeat compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    NSData *data = [NSData dataWithBytes:&param length:1];
    [self sendMessageWithCmdType:cmdType dataParam:data isRead:YES isRepeat:isRepeat repeatcount:0 compleBlock:compleBlock];
}

// 读取带参数
- (void)getDataWithCmdType:(L9_CarModelCmdType)cmdType data16Param:(uint16_t)param isRepeat:(BOOL)isRepeat compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    NSData *data = [NSData dataWithBytes:&param length:2];
    [self sendMessageWithCmdType:cmdType dataParam:data isRead:YES isRepeat:isRepeat repeatcount:0 compleBlock:compleBlock];
}

// 写入 参数 uint8_t
- (void)writeDataWithCmdType:(L9_CarModelCmdType)cmdType uint8Param:(uint8_t)param successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSData *data = [NSData dataWithBytes:&param length:1];
    [self sendMessageWithCmdType:cmdType dataParam:data isRepeat:YES repeatcount:0 successBlock:success failBlock:fail];
}

// 写入 参数 uint16_t
- (void)writeDataWithCmdType:(L9_CarModelCmdType)cmdType uint16Param:(uint16_t)param successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    NSData *data = [NSData dataWithBytes:&param length:2];
    [self sendMessageWithCmdType:cmdType dataParam:data isRepeat:YES repeatcount:0 successBlock:success failBlock:fail];
}

// 写入 参数 data
- (void)writeDataWithL9CmdType:(L9_CarModelCmdType)cmdType dataParam:(NSData *)param successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail{
    [self sendMessageWithCmdType:cmdType dataParam:param isRepeat:YES repeatcount:0 successBlock:success failBlock:fail];
}
// 统一发送消息-- 处理结果
- (void)sendMessageWithCmdType:(L9_CarModelCmdType)cmdType dataParam:(NSData *)param isRepeat:(BOOL)isRepeat repeatcount:(int)count successBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
        
    [self sendMessageWithCmdType:cmdType dataParam:param isRead:NO isRepeat:isRepeat repeatcount:count compleBlock:^(NSError *error, NSData *responseData) {
        if (error) {
            fail(error);
        }else {
            uint8_t resultCode ;
            [responseData getBytes:&resultCode range:NSMakeRange(0, responseData.length)];
            if ((resultCode == 0) || (resultCode == 1)) {
                success();
            }else {
                NSDictionary *userInfo = @{
                    @"description":[self returnErrorDescriptionWithErrorCode:resultCode],
                    @"errorCode":@(resultCode)
                };
                NSError *settingError = [NSError errorWithDomain:L9_CarModelErrorCodeDomain code:resultCode userInfo:userInfo];
                fail(settingError);
            }
        }
    }];
}

// 发送消息
- (void)sendMessageWithCmdType:(L9_CarModelCmdType)cmdType dataParam:(NSData *)param isRead:(BOOL)isRead isRepeat:(BOOL)isRepeat repeatcount:(int)count compleBlock:(IMNewCarModelCompletionBlock)compleBlock {
    
    count ++;
    
    IM_NewMessageFormat format;
    format.formatType = 0;
    format.isHasTab = 1;
    format.checkType = 1;
    format.isEncrypt = 0;
    format.dataType = 4;
    uint32_t tab = [self currentdateInterval];
    uint32_t cmd ;
    if (isRead) {
        cmd = cmdType & 0xbfffffff;
    }else {
        cmd = (uint32_t)cmdType | 0x40000000;
    }
    uint8_t cmdLength = [self cmdToDataWithCmd:cmd];
    
    IMTCANMessage *message = [IM_NewMessageFactory DedicatedMessageWithFormat:format key:0 tab:tab length:cmdLength + param.length source:0 target:0 cmd:cmd para:param];
    
    NSLog(@"🌹发送消息:专用组 ======================== checkType:%x -- dataType:%x -- isHasTab:%x -- isEncrypt:%x -- length:%x -- tab:%x -- key:%x -- source:%x -- target:%x -- cmd:%x -- para:%@  -- key:%@",message.newBody.format.checkType,message.newBody.format.dataType,message.newBody.format.isHasTab,message.newBody.format.isEncrypt,message.newBody.length,message.newBody.tab,message.newBody.key,message.DedicatedData.source,message.DedicatedData.target,message.DedicatedData.cmd,message.para,message.key);
    
    [[IMTCANManager sharedInstance] sendMessage:message withTimeOut:1.0 completion:^(NSError *error, NSData *responseData) {
        NSLog(@"=====================发送完成✅");
        // 读取时 无错误则解析数据 有错误返回错误 ，写入时 直接返回block 留给上层处理写入结果。
        if (isRead & !error) {
            [self analyzeDataWithData:responseData CmdType:cmdType];
        }
        if (error) {
            NSDictionary *userInfo = @{
                @"description":[self returnErrorDescriptionWithErrorCode:L9_CarModelErrorCodeTimeOut],
                @"errorCode":@(L9_CarModelErrorCodeTimeOut)
            };
            NSError *settingError = [NSError errorWithDomain:L9_CarModelErrorCodeDomain code:L9_CarModelErrorCodeRepeatFail userInfo:userInfo];
            
            if (isRepeat) {
                if (count > 2) {
                    compleBlock(settingError,responseData);
                }else {
                    NSLog(@"=================== 重试🐛🚗L9 ===============");
                    [self sendMessageWithCmdType:cmdType dataParam:param isRead:isRead isRepeat:isRepeat repeatcount:count compleBlock:compleBlock];
                }
            }else {
                compleBlock(settingError,responseData);
            }
        }else {
            compleBlock(error,responseData);
        }
    }];
    
}

// 统一解析数据 赋值属性
- (void)analyzeDataWithData:(NSData *)data CmdType:(L9_CarModelCmdType)cmdType {
    if (!data.length) {
        return;
    }
    NSLog(@"L9==================解析数据🌲- %@",data);
    if (IMTCarSeriesE20(self.LX_CarType)) {
        if (cmdType == L9_CarModelCmdTypeRealTimeVariable) { // 实时数据
            
            // E20默认速度单位为：km/h
            self.speedUnit = 0;
            
            E20_RealtimeInfoValues realtimeInfoValues ;
            [data getBytes:&realtimeInfoValues length:sizeof(E20_RealtimeInfoValues)];
            self.e20RealtimeInfoValues = realtimeInfoValues;
            
            self.currentSpeed = realtimeInfoValues.speed/100.0;
            self.thisTime_mileage = realtimeInfoValues.mileage/100.0;
            self.remainder_mileage = realtimeInfoValues.remainder_mileage/100.0;
            self.current_current = realtimeInfoValues.current/100.0;
            self.current_voltage = realtimeInfoValues.voltage/100.0;
            self.battery_percent = realtimeInfoValues.battery_percent/100.0;
            // 功率 、能耗 、速度 、温度 - 数组
            [self addValue:self.currentSpeed toArray:self.speeds limited:false];
            [self addValue:self.motor_temperature toArray:self.temperatures limited:true];
            self.power = self.current_current * self.current_voltage;
            [self addValue:self.power toArray:self.powers limited:false];
            self.energy = self.currentSpeed == 0 ? 0 : self.power/self.currentSpeed;
            [self addValue:self.energy toArray:self.tripEnergies limited:false];
            
        }else if (cmdType == L9_CarModelCmdTypeRealTimeState){ // 实时状态

            
        }else if (cmdType == L9_CarModelCmdTypeRealTimeError){ // 实时故障
            E20_ErrorValues errorValues ;
            [data getBytes:&errorValues length:sizeof(E20_ErrorValues)];
            self.e20ErrorValues = errorValues;
            
        }else if (cmdType == L9_CarModelCmdTypeRealTimeComplex){ // 综合实时数据
            E20_ExtRealTimeInfoValues extRealtimeInfoValues ;
            [data getBytes:&extRealtimeInfoValues length:sizeof(E20_ExtRealTimeInfoValues)];
            self.e20ExtRealtimeInfoValues = extRealtimeInfoValues;
            
            // 实时数据
            E20_RealtimeInfoValues realtimeInfoValues = extRealtimeInfoValues.realtime_info;
            self.currentSpeed = abs(realtimeInfoValues.speed)/100.0;
            self.thisTime_mileage = realtimeInfoValues.mileage/100.0;
            self.remainder_mileage = realtimeInfoValues.remainder_mileage/100.0;
            self.current_current = realtimeInfoValues.current/100.0;
            self.current_voltage = realtimeInfoValues.voltage/100.0;
            self.battery_percent = realtimeInfoValues.battery_percent/100.0;
            // 功率 、能耗 、速度 、温度 - 数组
            [self addValue:self.currentSpeed toArray:self.speeds limited:false];
            [self addValue:self.motor_temperature toArray:self.temperatures limited:true];
            self.power = self.current_current * self.current_voltage;
            [self addValue:self.power toArray:self.powers limited:false];
            self.energy = self.currentSpeed == 0 ? 0 : self.power/self.currentSpeed;
            [self addValue:self.energy toArray:self.tripEnergies limited:false];
            
            // 实时状态
            E20_StateValues stateValues = extRealtimeInfoValues.state;
            self.e20StateValues = stateValues;
            
            // 实时故障
            E20_ErrorValues errorValues = extRealtimeInfoValues.error;
            self.e20ErrorValues = errorValues;

        }else if (cmdType == L9_CarModelCmdTypeBrakeForce){ // 单次统计数据
            if (data.length == 5) {
                E20_RecordValue recordValue;
                [data getBytes:&recordValue length:sizeof(E20_RecordValue)];
                self.recordCount = recordValue.count;
            } else {
                E20_RecordValues recordValues ;
                [data getBytes:&recordValues length:sizeof(E20_RecordValues)];
                self.e20SingleRecordData = recordValues;
                double mile = (double)recordValues.mileage;
                double time = (double)recordValues.ride_time;
                self.averageSpeed = time == 0 ? 0 : 36*mile/time;
                self.thisTime_rideTime = recordValues.ride_time/60.0;
                self.power_on_time = recordValues.power_on_time/60.0;
            }
        }else if (cmdType == L9_CarModelCmdTypeSetMaxSpeed){ // 累计统计数据
            E20_StatisticsValues statisticsData ;
            [data getBytes:&statisticsData length:sizeof(E20_StatisticsValues)];
            self.e20StatisticsData = statisticsData;
            self.total_mileage = statisticsData.mileage/100.0;
        }
    } else {
        if (cmdType == L9_CarModelCmdTypeRealTimeVariable) { // 实时数据
            L9_RealtimeInfoValues realtimeInfoValues ;
            [data getBytes:&realtimeInfoValues length:sizeof(L9_RealtimeInfoValues)];
            self.realtimeInfoValues = realtimeInfoValues;
            
            self.currentSpeed = realtimeInfoValues.speed/100.0;
            self.thisTime_mileage = realtimeInfoValues.mileage/100.0;
            self.remainder_mileage = realtimeInfoValues.remainder_mileage/100.0;
            self.total_mileage = realtimeInfoValues.total_mileage/100.0;
            self.current_current = realtimeInfoValues.current/100.0;
            self.current_voltage = realtimeInfoValues.voltage/100.0;
            self.battery_percent = realtimeInfoValues.battery_percent/100.0;
            self.motor_temperature = realtimeInfoValues.motor_temperature;
            self.mos_temperature = realtimeInfoValues.mos_temperature;
            self.battery_temperature = realtimeInfoValues.battery_temperature;
            // 功率 、能耗 、速度 、温度 - 数组
            [self addValue:self.currentSpeed toArray:self.speeds limited:false];
            [self addValue:self.motor_temperature toArray:self.temperatures limited:true];
            self.power = self.current_current * self.current_voltage;
            [self addValue:self.power toArray:self.powers limited:false];
            self.energy = self.currentSpeed == 0 ? 0 : self.power/self.currentSpeed;
            [self addValue:self.energy toArray:self.tripEnergies limited:false];
            
        }else if (cmdType == L9_CarModelCmdTypeRealTimeState){ // 实时状态
            L9_StateValues stateValues ;
            [data getBytes:&stateValues length:sizeof(L9_StateValues)];
            self.runModel = stateValues.state_run_mode;
            self.stateValues = stateValues;
            self.lockSwitch = self.runModel == L9_CarModelRunModelLock;
            self.lightSwitch = (BOOL)stateValues.state_lamp;
            
        }else if (cmdType == L9_CarModelCmdTypeRealTimeError){ // 实时故障
            L9_ErrorValues errorValues ;
            [data getBytes:&errorValues length:sizeof(L9_ErrorValues)];
            self.errorValues = errorValues;
            
        }else if (cmdType == L9_CarModelCmdTypeRealTimeComplex){ // 综合实时数据
            L9_ExtRealTimeInfoValues extRealtimeInfoValues ;
            [data getBytes:&extRealtimeInfoValues length:sizeof(L9_ExtRealTimeInfoValues)];
            self.extRealtimeInfoValues = extRealtimeInfoValues;
            
            // 实时数据
            L9_RealtimeInfoValues realtimeInfoValues = extRealtimeInfoValues.realtime_info;
            self.currentSpeed = realtimeInfoValues.speed/100.0;
            self.thisTime_mileage = realtimeInfoValues.mileage/100.0;
            self.remainder_mileage = realtimeInfoValues.remainder_mileage/100.0;
            self.total_mileage = realtimeInfoValues.total_mileage/100.0;
            self.current_current = realtimeInfoValues.current/100.0;
            self.current_voltage = realtimeInfoValues.voltage/100.0;
            self.battery_percent = realtimeInfoValues.battery_percent;
            self.motor_temperature = realtimeInfoValues.motor_temperature;
            self.mos_temperature = realtimeInfoValues.mos_temperature;
            self.battery_temperature = realtimeInfoValues.battery_temperature;
            // 功率 、能耗 、速度 、温度 - 数组
            [self addValue:self.currentSpeed toArray:self.speeds limited:false];
            [self addValue:self.motor_temperature toArray:self.temperatures limited:true];
            self.power = self.current_current * self.current_voltage;
            [self addValue:self.power toArray:self.powers limited:false];
            self.energy = self.currentSpeed == 0 ? 0 : self.power/self.currentSpeed;
            [self addValue:self.energy toArray:self.tripEnergies limited:false];
            
            // 实时状态
            L9_StateValues stateValues = extRealtimeInfoValues.state;
            self.runModel = stateValues.state_run_mode;
            self.stateValues = stateValues;
            self.lockSwitch = self.runModel == L9_CarModelRunModelLock;
            self.lightSwitch = (BOOL)stateValues.state_lamp;
            
            // 实时故障
            L9_ErrorValues errorValues = extRealtimeInfoValues.error;
            self.errorValues = errorValues;

        }else if (cmdType == L9_CarModelCmdTypeSingleData){ // 单次统计数据
            L9_RecordValues recordValues ;
            [data getBytes:&recordValues length:sizeof(L9_RecordValues)];
            double mile = (double)recordValues.mileage;
            double time = (double)recordValues.ride_time;
            self.averageSpeed = time == 0 ? 0 : 36*mile/time;
            self.singleRecordData = recordValues;
            self.currentMaxSpeed = recordValues.max_speed/100.0;
            self.thisTime_rideTime = recordValues.ride_time/60.0;
            self.power_on_time = recordValues.power_on_time/60.0;
        }else if (cmdType == L9_CarModelCmdTypeCumulativeData){ // 累计统计数据
            L9_StatisticsValues statisticsData ;
            [data getBytes:&statisticsData length:sizeof(L9_StatisticsValues)];
            self.statisticsData = statisticsData;
            self.total_mileage = statisticsData.mileage/100.0;
            
        }else if (cmdType == L9_CarModelCmdTypeComplexSetting){ // 综合设置
            L9_SettingParams settingParams ;
            [data getBytes:&settingParams length:sizeof(L9_SettingParams)];
            self.settingParams = settingParams;
            self.lockSwitch = (BOOL)settingParams.lock_mode;
            self.zeroSpeedStart = (BOOL)settingParams.zero_startup;
            self.automaticCruise = (BOOL)settingParams.auto_cruise;
            self.speedUnit = settingParams.speed_unit;
            self.accelerationForce = settingParams.accelerate_force;
            self.brakeForce = settingParams.brake_force;
            self.limitSpeed = settingParams.limit_speed/100.0;
            self.rideModel = settingParams.driver_mode;
            self.ambientLightSwitch = (settingParams.ambient_light_mode == 1) || (settingParams.ambient_light_mode == 2);
            self.turnLightSwitch = (settingParams.ambient_light_mode == 3) || (settingParams.ambient_light_mode == 2);
            self.forceSmartSwitch = settingParams.smart_acc == 1;
            self.speedLimitSwitch = settingParams.safe_speed_limit == 1;
            self.downhillAssistSwitch = settingParams.downhill_assist == 1;
            self.uphillAssistSwitch = settingParams.uphill_assist == 1;
            
        }else if (cmdType == L9_CarModelCmdTypeZeroSpeedStart){ // 零速启动
            uint8_t zeroSpeedStart;
            [data getBytes:&zeroSpeedStart range:NSMakeRange(0, data.length)];
            self.zeroSpeedStart = (BOOL)zeroSpeedStart;
            
        }else if (cmdType == L9_CarModelCmdTypeAutomaticCruise){ // 自动巡航
            uint8_t automaticCruise;
            [data getBytes:&automaticCruise range:NSMakeRange(0, data.length)];
            self.automaticCruise = (BOOL)automaticCruise;
            
        }else if (cmdType == L9_CarModelCmdTypeSpeedUnit){ // 速度单位
            uint8_t speedUnit;
            [data getBytes:&speedUnit range:NSMakeRange(0, data.length)];
            self.speedUnit = speedUnit;
            
        }else if (cmdType == L9_CarModelCmdTypeAccelerationForce){  // 加速力度
            uint8_t accelerationForce;
            [data getBytes:&accelerationForce range:NSMakeRange(0, data.length)];
            self.accelerationForce = accelerationForce;
            
        }else if (cmdType == L9_CarModelCmdTypeBrakeForce){ // 刹车力度
            uint8_t brakeForce;
            [data getBytes:&brakeForce range:NSMakeRange(0, data.length)];
            self.brakeForce = brakeForce;
            
        }else if (cmdType == L9_CarModelCmdTypeSetMaxSpeed){ // 车速限制
            uint16_t limitSpeed;
            [data getBytes:&limitSpeed range:NSMakeRange(0, data.length)];
            self.limitSpeed = limitSpeed/100.0;
            
        }else if (cmdType == L9_CarModelCmdTypeRideModel){ // 骑行模式
            L9_CarModelRideModel rideModel;
            [data getBytes:&rideModel range:NSMakeRange(0, data.length)];
            self.rideModel = rideModel;
            
        }else if (cmdType == L9_CarModelCmdTypeLockCar){ // 锁车模式
            int8_t lockSwitch;
            [data getBytes:&lockSwitch range:NSMakeRange(0, data.length)];
            self.lockSwitch = (BOOL)lockSwitch;
            
        }else if (cmdType == L9_CarModelCmdTypeSettingAmbientLightSwitch){ // 氛围灯开关
            int8_t ambientSwitch;
            [data getBytes:&ambientSwitch range:NSMakeRange(0, data.length)];
            self.ambientLightSwitch = ambientSwitch != 3;
            
        }else if (cmdType == L9_CarModelCmdTypeSetLight){ // 前灯开关
            int8_t lightSwitch;
            [data getBytes:&lightSwitch range:NSMakeRange(0, data.length)];
            self.lightSwitch = (BOOL)lightSwitch;
            
        }else if (cmdType == L9_CarModelCmdTypeSettingForceAdjustSmart){ // 加速力度智能调节
            int8_t forceSmartSwitch;
            [data getBytes:&forceSmartSwitch range:NSMakeRange(0, data.length)];
            self.forceSmartSwitch = (BOOL)forceSmartSwitch;
        }else if (cmdType == L9_CarModelCmdTypeSettingSpeedLimitState){ // 安全限速开关
            int8_t speedLimitSwitch;
            [data getBytes:&speedLimitSwitch range:NSMakeRange(0, data.length)];
            self.speedLimitSwitch = (BOOL)speedLimitSwitch;
        }else if (cmdType == L9_CarModelCmdTypeDownhillAssist){ // 下坡辅助
            int8_t downhillAssistSwitch;
            [data getBytes:&downhillAssistSwitch range:NSMakeRange(0, data.length)];
            self.downhillAssistSwitch = (BOOL)downhillAssistSwitch;
        }else if (cmdType == L9_CarModelCmdTypeUphillAssist){ // 上坡辅助
            int8_t uphillAssistSwitch;
            [data getBytes:&uphillAssistSwitch range:NSMakeRange(0, data.length)];
            self.uphillAssistSwitch = (BOOL)uphillAssistSwitch;
        }
    }
}

// 获取cmd的实际长度
- (uint8_t)cmdToDataWithCmd:(uint32_t)cmd {
    uint8_t cmdLength = 0;
    uint32_t temp = cmd&0x03FFFFFF;
    if(temp < 0x20) {  // 5位以内
        cmdLength = 1;
    } else if(temp < 0x1000){ // 12位以内
        cmdLength = 2;
    } else if(temp < 0x80000) { // 19位以内
        cmdLength = 3;
    } else { // if(temp < 0x4000000)//26位以内
        cmdLength = 4;
    }
    return cmdLength;
}

// 返回错误信息
- (NSString *)returnErrorDescriptionWithErrorCode:(L9_CarModelErrorCode)errorCode {
    NSString *errorDescription = @"";
    if (errorCode == L9_CarModelErrorCodeSuccess) {
        errorDescription = @"操作正确";
    }else if (errorCode == L9_CarModelErrorCodeNotActive) {
        errorDescription = @"无错误，指令已生效";
    }else if (errorCode == L9_CarModelErrorCodeRepeat) {
        errorDescription = @"重复操作";
    }else if (errorCode == L9_CarModelErrorCodeParamError) {
        errorDescription = @"参数错误";
    }else if (errorCode == L9_CarModelErrorCodeNotSupport) {
        errorDescription = @"目标设备不支持此操作";
    }else if (errorCode == L9_CarModelErrorCodeNotAllowed) {
        errorDescription = @"当前状态不允许进行此操作";
    }else if (errorCode == L9_CarModelErrorCodeNotOperation) {
        errorDescription = @"无操作权限";
    }else if (errorCode == L9_CarModelErrorCodeExecutionError) {
        errorDescription = @"内部执行错误";
    }else if (errorCode == L9_CarModelErrorCodeTimeOut) {
        errorDescription = @"消息超时";
    }else if (errorCode == L9_CarModelErrorCodeRepeatFail) {
        errorDescription = @"重试错误";
    }else {
        errorDescription = @"设置失败";
    }
    return errorDescription;
}

// 返回当前时间戳的后四位
-(uint32_t)currentdateInterval {
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    timeSp = [timeSp substringWithRange:NSMakeRange(timeSp.length - 4, 4)];
    return (uint32_t)[timeSp intValue];
}

// 获取车辆错误代码的提示语
- (NSString *)getCarRealTimeErrorTipWithError:(L9_ErrorValues)errors {
    NSString *errorStr = @"";
    if (errors.error_controller == 1) {
        errorStr = [errorStr stringByAppendingString:@"控制器故障  "];
    }else if (errors.error_motor == 1){
        errorStr = [errorStr stringByAppendingString:@"电机故障  "];
    }else if (errors.error_battery == 1){
        errorStr = [errorStr stringByAppendingString:@"电池故障  "];
    }else if (errors.error_voltage == 1){
        errorStr = [errorStr stringByAppendingString:@"欠压故障  "];
    }else if (errors.error_voltage == 2){
        errorStr = [errorStr stringByAppendingString:@"过压故障  "];
    }else if (errors.error_brake_handle == 1){
        errorStr = [errorStr stringByAppendingString:@"刹车把手故障  "];
    }else if (errors.error_throttle_handle == 1){
        errorStr = [errorStr stringByAppendingString:@"油门把手故障  "];
    }else if (errors.error_hmic_RX == 1){
        errorStr = [errorStr stringByAppendingString:@"仪表接收控制器数据异常  "];
    }else if (errors.error_mc_RX == 1){
        errorStr = [errorStr stringByAppendingString:@"控制器接收仪表数据异常  "];
    }else if (errors.error_mos_over_temp == 1){
        errorStr = [errorStr stringByAppendingString:@"MOS温度过高  "];
    }else if (errors.error_motor_over_temp == 1){
        errorStr = [errorStr stringByAppendingString:@"电机温度过高  "];
    }else if (errors.error_battery_over_temp == 1){
        errorStr = [errorStr stringByAppendingString:@"电池温度过高"];
    }
    return errorStr;
}
#pragma mark ==== 标准组获取软件版本号
- (void)getCarVersionSuccessBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    [self getCarFirmwareAndDeviceNumWithCompleBlock:^(NSError *error, NSData *responseData) {
        if (error) {
            fail(error);
        }else {
            NSUInteger indexOffset = 0;
            NSString *carVersion = @"";
            NSString *MTStr = @"";
            NSString *BTStr = @"";
            NSString *carBtdVersion = @"";
            NSString *MTBtdStr = @"";
            NSString *BTBtdStr = @"";
            self.versionData = [NSMutableArray arrayWithCapacity:1];
            do {
                // 设备号
                uint8_t carNum;
                [responseData getBytes:&carNum range:NSMakeRange(indexOffset++, 1)];
                // 应用程序版本号
                uint32_t mainVersion ;
                [responseData getBytes:&mainVersion range:NSMakeRange(indexOffset, 4)];
                indexOffset += 4;
                NSString *mainVersionStr = [NSString stringWithFormat:@"%d.%d.%d",(mainVersion & 0xff000000) >> 24,(mainVersion & 0x00ff0000) >> 16,(mainVersion & 0x0000ffff) >> 0];
                // 引导程序版本号
                uint32_t guiderVersion ;
                [responseData getBytes:&guiderVersion range:NSMakeRange(indexOffset, 4)];
                indexOffset += 4;
                NSString *guiderVersionStr = [NSString stringWithFormat:@"%d.%d.%d",(guiderVersion & 0xff000000) >> 24,(guiderVersion & 0x00ff0000) >> 16,(guiderVersion & 0x0000ffff) >> 0];

                if (carNum == 0x31) {
                    MTStr = mainVersionStr;
                    MTBtdStr = guiderVersionStr;
                    self.mcVersion = mainVersionStr;
                    NSDictionary * mtDic = @{@"device":@(0x31),@"appVersion":mainVersionStr,@"blVersion":guiderVersionStr};
                    if (![self.versionData containsObject:mtDic]) {
                        [self.versionData addObject:mtDic];
                    }
                }else if (carNum == 0x32){
                    BTStr = mainVersionStr;
                    BTBtdStr = guiderVersionStr;
                    self.btVersion = mainVersionStr;
                    NSDictionary * btDic = @{@"device":@(0x32),@"appVersion":mainVersionStr,@"blVersion":guiderVersionStr};
                    if (![self.versionData containsObject:btDic]) {
                        [self.versionData addObject:btDic];
                    }
                }
                
                NSLog(@"L9🐼🐼🐼🐼🐼🐼🐼🐼🐼🐼 设备号：%d   应用程序板本：%@   引导程序版本：%@",carNum,mainVersionStr,guiderVersionStr);
            } while (indexOffset<responseData.length);
            carVersion = [carVersion stringByAppendingString:[NSString stringWithFormat:@"%@(MC),%@(BT)",MTStr,BTStr]];
            carBtdVersion = [carBtdVersion stringByAppendingString:[NSString stringWithFormat:@"%@,%@",MTBtdStr,BTBtdStr]];
            self.carVersion = carVersion;
            self.carBootloaderVersion = carBtdVersion;
            success();
        }
    }];
}

#pragma mark ==== 标准组获取硬件版本号
- (void)getCarhwVersionSuccessBlock:(IMNewCarModelSettingSuccessBlock)success failBlock:(IMNewCarModelSettingFailBlock)fail {
    [self getCarFirmwareAndDeviceNumWithCompleBlock:^(NSError *error, NSData *responseData) {
        if (error) {
            fail(error);
        }else {
            NSUInteger indexOffset = 0;
            self.hwVersionData = [NSMutableArray arrayWithCapacity:1];
            do {
                // 设备号
                uint8_t carNum;
                [responseData getBytes:&carNum range:NSMakeRange(indexOffset++, 1)];
                
                // 应用程序版本号
                uint16_t mainVersion ;
                [responseData getBytes:&mainVersion range:NSMakeRange(indexOffset, 2)];
                indexOffset += 2;
                
                NSString *mainVersionStr = [NSString stringWithFormat:@"%d.%d",(mainVersion & 0x00ff0000) >> 8,(mainVersion & 0x0000ffff) >> 0];
                for (NSDictionary *temp in self.versionData) {
                    if ([temp.allKeys containsObject:@(carNum)]) {
                        [temp setValue:mainVersionStr forKey:@"hwVersion"];
                    }
                }
                NSLog(@"l9硬件🐼🐼🐼🐼🐼🐼🐼🐼🐼🐼 设备号：%d   应用程序板本：%@ ---- %@",carNum,mainVersionStr,self.versionData);
            } while (indexOffset<responseData.length);
            success();
        }
    }];
}

// 保存车辆密码
- (void)saveCarBlePassword {
    NSData *codedata = [IMFunction AES128EncryptECB:[IMFunction strToAscll:self.blePassword]];
    NSString *key = [NSString stringWithFormat:@"CarBlePassword_%@_%@",self.lx_bleName,self.lx_sn];
    NSDictionary *dict = @{@"password":codedata, @"timestamp":[IMFunction getTimestampSince1970]};
    NSLog(@"将新密码保存到本地================== %@",dict);
    //将新密码保存到本地
    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:key];
}

// 获取车辆里的蓝牙密码
- (void)loadLocalCarBlePassword {
    NSString *key = [NSString stringWithFormat:@"CarBlePassword_%@_%@",self.lx_bleName,self.lx_sn];
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    NSLog(@"获取本地蓝牙密码================== %@",dict);
    if (dict) {
        double localTime = [dict[@"timestamp"] doubleValue];
        double nowTime = [[IMFunction getTimestampSince1970] doubleValue];
        if (nowTime - localTime <= 2592000) {
            NSString *code = [IMFunction convertDataToHexStr:[IMFunction AES128DecryptECB:dict[@"password"]]];
            self.blePassword = code;
            NSLog(@"获取本地蓝牙密码OK================== %@",code);
        }
    }
}

- (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];

    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];

    return string;
}

@end
